import { UnorderedListOutlined, DownOutlined } from '@ant-design/icons';
import { Dropdown, Menu, Typography, message, Modal, Tooltip } from 'antd';
import React, { useRef, useEffect, useState } from 'react';
import { history, useModel } from 'umi';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
// import { planEditStatus, planDelete } from '@/services/operate';
import moment from 'moment';
import BigNumber from 'bignumber.js';

// import CalendarModel from '../calendar-model';
import styles from './style.less';
import { isEmpty, every } from 'lodash';

const { confirm } = Modal;
const { Text } = Typography;

type Props = {
  fullCalendarRef: any;
  segmentValue: string; // 1--计划
  initialEvent: any[];
  initialActivity: any[];
  getViewSearchData: () => void;
};

const EnumDotBgcolor = {
  0: '#bbbbb9',
  1: '#ffbe64',
  2: '#37e174',
  3: '#3379ff',
};
const EnumBodyBgcolor = {
  0: '#f2f2f2',
  1: '#fff7e5',
  2: '#c0eac7',
  3: '#ecf3fd',
};
const EnumBodyBordercolor = {
  0: '#e9e9e7',
  1: '#ffe9be',
  2: '#37e174',
  3: '#bbd3fd',
};
// 计划名称--颜色
const EnumPlanTextcolor = {
  0: '#424240',
  1: '#424240',
  2: '#424240',
  3: '#424240',
};

const CalendarBody: React.FC<Props> = ({
  fullCalendarRef,
  segmentValue,
  initialEvent,
  initialActivity,
  getViewSearchData,
}) => {
  const wrapRef = useRef<any>(null);
  const [eventWidth, setEventWidth] = useState(0);
  const [visibleModel, setVisibleModel] = useState(false);
  const [dataModel, setDataModel] = useState('');
  const { initialState, setInitialState } = useModel('@@initialState');

  useEffect(() => {
    // 当组件挂载后，获取 div 的宽度和高度
    if (wrapRef.current) {
      const width = wrapRef.current.getBoundingClientRect().width || 0;
      setEventWidth(Number((Number(width) / 7).toFixed(0)));
    }
  }, []);

  const goAddPage = (date: any) => {
    setInitialState({
      ...initialState,
      calendarAddDate: moment(date).format('YYYY-MM-DD'),
    });
    setTimeout(() => {
      history.push(`/operate/package/add`);
    });
  };

  const handleOperate = (type: string, record: any) => {
    if (type === '编辑') {
      if (record.viewStatus === 2) {
        confirm({
          content: `当前计划正在生效中，编辑后会影响计划效果数据(量销售额、增量销售额百分比)，请确认是否编辑该计划?`,
          onOk() {
            history.push(`/operate/package/modify/${record.paramId}`);
          },
          onCancel() {},
        });
      } else {
        history.push(`/operate/package/modify/${record.paramId}`);
      }
    }
    if (type === '查看') {
      history.push(`/operate/package/read/${record.paramId}`);
    }
    if (type === '开启' || type === '终止') {
      confirm({
        content: `计划${type}后会影响计划效果数据(增量销售额、增量销售额百分比)，是否确认${type}该计划?`,
        async onOk() {
          // const { code, data } = await planEditStatus({
          //   id: record.paramId,
          //   status: type === '开启' ? 1 : 2,
          // });
          // if (code === 200) {
          //   message.success(`计划${type}成功`);
          //   getViewSearchData();
          // }
        },
        onCancel() {},
      });
    }
    if (type === '删除') {
      confirm({
        content: `是否确认${type}该计划?`,
        async onOk() {
          // const { code } = await planDelete({
          //   id: record.paramId,
          // });
          // if (code === 200) {
          //   message.success(`计划${type}成功`);
          //   getViewSearchData();
          // }
        },
        onCancel() {},
      });
    }
  };

  const getItems = (record: any) => {
    return (
      <Menu>
        <Menu.Item key="submit">
          <a
            onClick={(e) => {
              handleOperate('查看', record);
            }}
          >
            查看
          </a>
        </Menu.Item>
        {![0].includes(record.viewStatus) && (
          <Menu.Item key="sync">
            <a
              onClick={() => {
                handleOperate('编辑', record);
              }}
            >
              编辑
            </a>
          </Menu.Item>
        )}
        {/* 帆哥指导---打包票的开启和终止逻辑 */}
        {/* viewStatus 0-失效，1-执行中不生效，2-执行中生效，3-未开始 */}
        {/* planStatus 1-开启中，2-已终止 */}
        {[2].includes(record.planStatus) && [1, 2, 3].includes(record.viewStatus) && (
          <Menu.Item key="open">
            <a
              onClick={() => {
                handleOperate('开启', record);
              }}
            >
              开启
            </a>
          </Menu.Item>
        )}
        {[1].includes(record.planStatus) && [1, 2, 3].includes(record.viewStatus) && (
          <Menu.Item key="close">
            <a
              onClick={() => {
                handleOperate('终止', record);
              }}
            >
              终止
            </a>
          </Menu.Item>
        )}
        {/* 1. 未来计划支持删除 */}
        {[3].includes(record.viewStatus) && (
          <Menu.Item key="delete">
            <a
              onClick={() => {
                handleOperate('删除', record);
              }}
            >
              删除
            </a>
          </Menu.Item>
        )}
      </Menu>
    );
  };

  const handleOpen = (itemData: string) => {
    setVisibleModel(true);
    setDataModel(itemData);
    setTimeout(() => {
      setVisibleModel(false);
    });
  };

  // 自定义事件内容---计划
  const renderEventContent = (eventInfo: any) => {
    const extendedProps = eventInfo.event._def.extendedProps;
    console.log('extendedProps', extendedProps);
    if (eventWidth === 0) return null;
    return (
      <div
        className={styles['event-body']}
        style={{
          padding: 5,
          backgroundColor: EnumBodyBgcolor[extendedProps.viewStatus],
          borderColor: EnumBodyBordercolor[extendedProps.viewStatus],
        }}
      >
        <div className={styles['event-title']}>
          <div className={styles['title-left']}>
            {/* <Text ellipsis={{ tooltip: extendedProps.planName + extendedProps.createdAt }}> */}
            <span
              className={styles['title-dot']}
              style={{ backgroundColor: EnumDotBgcolor[extendedProps.viewStatus] }}
            />
            <Tooltip title={extendedProps.planName + extendedProps.updatedAt}>
              <span
                className={styles['title-style']}
                style={{
                  color: [1, 2, 3].includes(extendedProps.alertStatus)
                    ? '#c62d2e'
                    : EnumPlanTextcolor[extendedProps.viewStatus],
                }}
              >
                {extendedProps.planName}
              </span>
            </Tooltip>
            {/* </Text> */}
            {/* {extendedProps.createdAt} */}
            {extendedProps.updatedAt}
          </div>
          <div className={styles['title-right']}>
            <Dropdown overlay={getItems(extendedProps)}>
              <UnorderedListOutlined
                style={{
                  color: EnumPlanTextcolor[extendedProps.viewStatus],
                }}
              />
            </Dropdown>
          </div>
        </div>
        <div style={{ display: 'flex', marginTop: 4 }}>
          {extendedProps.rankDatas &&
            !every(extendedProps.rankDatas, isEmpty) &&
            extendedProps.rankDatas.map((item: any, index: number) => {
              if (isEmpty(item)) {
                return (
                  <>
                    <div
                      className={styles['event-solo']}
                      style={{ width: eventWidth - 10, opacity: 0 }}
                      key={index}
                    />
                  </>
                );
              }
              return (
                <>
                  <Tooltip
                    key={index}
                    title={
                      <div>
                        {`增量销售额:${(item?.incrementalSales || 0).toLocaleString()}`}
                        <br />
                        {`增量销售额百分比:${(
                          Number(item?.incrementalSalesPercent || 0) * 100
                        ).toFixed(2)}%`}
                      </div>
                    }
                  >
                    <div
                      className={styles['event-solo']}
                      style={{ width: eventWidth - 10 }}
                      key={index}
                    >
                      {item.hasData && item.hasData === 1 ? '*' : ''}增量销售额:
                      {(item?.incrementalSales || 0).toLocaleString()} &nbsp;&nbsp;
                      {item.hasData && item.hasData === 1 ? '*' : ''}增量销售额百分比:
                      {(Number(item?.incrementalSalesPercent || 0) * 100).toFixed(2)}%
                    </div>
                  </Tooltip>
                </>
              );
            })}
        </div>
      </div>
    );
  };

  // 自定义天内容---活动
  const renderDayCellContent = (item: any) => {
    const itemData = moment(new Date(item.date)).format('YYYY-MM-DD');
    // const itemDataTime = moment(new Date(item.date)).format('YYYY-MM-DD HH:mm:ss');
    const rankItem = initialActivity.find((items: any) => items.rankDate === itemData);
    return (
      <div className={styles['day-wrap']} style={{ minHeight: segmentValue === '1' ? 1 : 150 }}>
        {/* <span>
            {new Date(item.date).getTime() == new Date(new Date().setHours(0, 0, 0, 0)).getTime()
              ? '新增'
              : null}
          </span> */}
        {/* 如果是今天 直接给他私有样式--显示出来 */}
        <span
          className={styles['day-icon']}
          onClick={() => {
            goAddPage(item.date);
          }}
        >
          {/* {new Date(item.date).getTime() === new Date(new Date().setHours(0, 0, 0, 0)).getTime()
            ? '今天'
            : ''} */}
          <span style={{ display: 'inline-block', marginLeft: 6 }}>
            {segmentValue == '1' &&
            new Date(item.date).getTime() >= new Date(new Date().setHours(0, 0, 0, 0)).getTime()
              ? '新增'
              : null}
          </span>
        </span>

        <div className={styles['day-cell']} style={{ width: eventWidth }}>
          <span style={{ color: '#333' }}>{item.date.getDate()}</span>
        </div>

        {segmentValue !== '1' && rankItem && rankItem.rankDataList ? (
          <div
            className={styles['day-body']}
            style={{
              width: eventWidth,
            }}
          >
            <div
              className={styles['list-body']}
              onClick={() => {
                handleOpen(itemData);
              }}
            >
              {rankItem.rankDataList.map(
                (rankDataItem: any, index: number) =>
                  index < 5 && (
                    <div className={styles['list-solo']} key={index}>
                      {index + 1}、{rankDataItem.activity}
                    </div>
                  ),
              )}
              {rankItem.rankDataList.length > 4 && (
                <div className={styles['list-solo']}>
                  <DownOutlined />
                </div>
              )}
            </div>
          </div>
        ) : null}
      </div>
    );
  };

  // // 点击事件
  // const handleEventClick = (clickInfo: any) => {
  //   console.log('我点击了事件', clickInfo);
  // };
  const getSelfHeight = (eventList: any) => {
    if (isEmpty(eventList)) {
      return 900;
    }
    if (eventList.length > 12) {
      return 900 + (eventList.length - 12) * 60;
    }
    return 900;
  };

  console.log('initialEvent===', initialEvent);

  return (
    <div ref={wrapRef} className={styles['calendar-containt']}>
      <FullCalendar
        initialDate="2024-09-01" // 设置初始化--时间
        height={getSelfHeight(initialEvent)}
        ref={fullCalendarRef}
        plugins={[dayGridPlugin]}
        headerToolbar={false}
        initialView="dayGridMonth"
        firstDay={1} // 设置一周的第一天为周一
        editable={false} // 设置日历不可编辑
        handleWindowResize={false} //随浏览器窗口变化
        dayMaxEvents={false} // 日历的每一个格子大小是否随便事件数变化
        locale="zh-cn"
        events={segmentValue === '1' ? initialEvent : []} // 自定义事件数据体
        // 前面有空格 会自动占位上去  ---按照start进行排序
        eventOrder="start" //flagIndex   start     updatedAt
        // eventOrder={(event1, event2) => {
        //   console.log('1', event1);
        //   console.log('event2', event2);
        //   return event1.updatedAt > event2.updatedAt ? -1 : 1;
        // }}
        // eventOrder={() => {
        //   return 1;
        // }}
        // eventOrderStrict={true}
        views={{
          dayGridMonth: {
            dayCellContent: renderDayCellContent,
          },
        }}
        eventContent={renderEventContent} // 自定义事件渲染
        // eventClick={handleEventClick} // 点击事件
      />

      {/* <CalendarModel
        visibleModel={visibleModel}
        dataModel={dataModel}
        segmentValue={segmentValue}
      /> */}
    </div>
  );
};

export default CalendarBody;
